<template>
  <div class="admin-teams">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="队伍名称">
          <el-input v-model="searchForm.name" placeholder="请输入队伍名称" />
        </el-form-item>
        <el-form-item label="活动区域">
          <el-input v-model="searchForm.activityArea" placeholder="请输入活动区域" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.auditStatus" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="待审核" :value="0" />
            <el-option label="已通过" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="teamList" border stripe v-loading="tableLoading" style="width: 100%;">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="队伍名称" min-width="200">
          <template #default="{ row }">
            <div class="team-name">
              <el-avatar :src="row.logo" :size="40" />
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="activityArea" label="活动区域" width="150" />
        <el-table-column prop="memberCount" label="成员数" width="100">
          <template #default="{ row }">
            {{ row.memberCount }} 人
          </template>
        </el-table-column>
        <el-table-column prop="foundingDate" label="成立时间" width="150">
          <template #default="{ row }">
            {{ formatDate(row.foundingDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="auditStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.auditStatus)">
              {{ getStatusText(row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.auditStatus === 0"
              link 
              type="primary" 
              @click="handleApprove(row)"
            >通过</el-button>
            <el-button 
              v-if="row.auditStatus === 0"
              link 
              type="danger" 
              @click="handleReject(row)"
            >拒绝</el-button>
            <el-button link type="primary" @click="handleDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="队伍详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="队伍名称" :span="2">
          <div class="team-name">
            <el-avatar :src="currentDetail.logo" :size="60" />
            <span>{{ currentDetail.name }}</span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="活动区域">{{ currentDetail.activityArea }}</el-descriptions-item>
        <el-descriptions-item label="队长ID">{{ currentDetail.leaderId }}</el-descriptions-item>
        <el-descriptions-item label="成员数">{{ currentDetail.memberCount }} 人</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentDetail.auditStatus)">
            {{ getStatusText(currentDetail.auditStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="成立时间">{{ formatDate(currentDetail.foundingDate) }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ currentDetail.contactInfo }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(currentDetail.createTime) }}</el-descriptions-item>
        <el-descriptions-item v-if="currentDetail.rejectReason" label="拒绝原因" :span="2">{{ currentDetail.rejectReason }}</el-descriptions-item>
        <el-descriptions-item label="队伍简介" :span="2">{{ currentDetail.description }}</el-descriptions-item>
      </el-descriptions>

      <!-- 成员列表 -->
      <div class="member-list">
        <div class="section-title">成员列表</div>
        <el-table 
          :data="Array.isArray(currentDetail.members) ? currentDetail.members : []" 
          border
          style="width: 100%; table-layout: fixed;"
        >
          <el-table-column prop="name" label="姓名" min-width="150">
            <template #default="{ row }">
              <div class="member-info">
                <el-avatar v-if="row.avatar" :src="row.avatar" :size="30" />
                <span>{{ row.name || '未设置姓名' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="role" label="角色" width="120">
            <template #default="{ row }">
              <el-tag :type="getMemberRoleType(row.role)">
                {{ getMemberRoleText(row.role) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="joinTime" label="加入时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.joinTime) }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getTeamList, getTeamDetail, approveTeam, rejectTeam, getTeamMembers } from '@/api/team'

// ResizeObserver 防抖处理 - 解决 ResizeObserver loop completed with undelivered notifications 错误
if (typeof window !== 'undefined' && window.ResizeObserver) {
  const debounce = (callback, delay) => {
    let timeoutId;
    return function(...args) {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => callback.apply(this, args), delay);
    };
  };
  
  const OriginalResizeObserver = window.ResizeObserver;
  window.ResizeObserver = class ResizeObserver extends OriginalResizeObserver {
    constructor(callback) {
      super(debounce(callback, 20));
    }
  };
}

// 搜索表单
const searchForm = reactive({
  name: '',
  activityArea: '',
  auditStatus: '',
  dateRange: []
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 队伍列表
const teamList = ref([])
const tableLoading = ref(false)
const dataInitialized = ref(false)

// 详情对话框
const detailDialogVisible = ref(false)
const currentDetail = ref({
  members: []
})

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'warning',   // 待审核
    1: 'success',   // 已通过
    2: 'danger'     // 已拒绝
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝'
  }
  return texts[status] || '未知'
}

// 日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
}

// 获取队伍列表
const loadTeamList = async () => {
  tableLoading.value = true
  dataInitialized.value = false
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      name: searchForm.name || undefined,
      activityArea: searchForm.activityArea || undefined,
      auditStatus: searchForm.auditStatus === '' ? undefined : searchForm.auditStatus,
      startTime: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : undefined,
      endTime: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : undefined
    }
    
    const res = await getTeamList(params)
    if (res && res.code === 200) {
      teamList.value = res.data.list
      total.value = res.data.total
      
      setTimeout(() => {
        dataInitialized.value = true
      }, 100)
    } else {
      ElMessage.error(res?.message || '获取队伍列表失败')
    }
  } catch (error) {
    console.error('加载队伍列表出错:', error)
    ElMessage.error('获取队伍列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 查看详情
const handleDetail = async (row) => {
  try {
    // 重置currentDetail，确保每次打开详情都有一个新的空members数组
    currentDetail.value = {
      members: []
    }
    
    // 先打开对话框，再加载数据
    detailDialogVisible.value = true
    
    const res = await getTeamDetail(row.id)
    if (res && res.code === 200) {
      // 先获取基本数据
      currentDetail.value = {
        ...res.data,
        members: []
      }
      
      // 然后在nextTick中获取成员数据，避免同时触发多次重排
      nextTick(async () => {
        try {
          // 获取队伍成员
          const membersRes = await getTeamMembers(row.id)
          if (membersRes && membersRes.code === 200) {
            // 处理后端返回的数据结构，确保正确获取members数组
            if (Array.isArray(membersRes.data)) {
              currentDetail.value.members = membersRes.data
            } else if (membersRes.data && membersRes.data.list && Array.isArray(membersRes.data.list)) {
              // 后端返回了分页数据结构，取list字段
              currentDetail.value.members = membersRes.data.list
            } else {
              console.error('成员数据格式不正确:', membersRes.data)
              currentDetail.value.members = []
            }
          }
        } catch (error) {
          console.error('获取成员列表出错:', error)
          currentDetail.value.members = []
        }
      })
    } else {
      ElMessage.error(res?.message || '获取队伍详情失败')
    }
  } catch (error) {
    console.error('获取队伍详情出错:', error)
    ElMessage.error('获取队伍详情失败')
  }
}

// 处理审核通过
const handleApprove = (row) => {
  ElMessageBox.confirm(
    '确认通过该队伍？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await approveTeam(row.id)
      if (res && res.code === 200) {
        ElMessage.success('审核通过成功')
        loadTeamList()
      } else {
        ElMessage.error(res?.message || '审核操作失败')
      }
    } catch (error) {
      console.error('审核队伍出错:', error)
      ElMessage.error('审核操作失败，请重试')
    }
  }).catch(() => {})
}

// 处理审核拒绝
const handleReject = (row) => {
  ElMessageBox.prompt('请输入拒绝原因', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请输入拒绝原因'
  }).then(async ({ value }) => {
    try {
      const res = await rejectTeam(row.id, value)
      if (res && res.code === 200) {
        ElMessage.success('已拒绝该队伍')
        loadTeamList()
      } else {
        ElMessage.error(res?.message || '拒绝操作失败')
      }
    } catch (error) {
      console.error('拒绝队伍出错:', error)
      ElMessage.error('拒绝操作失败，请重试')
    }
  }).catch(() => {})
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadTeamList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  currentPage.value = 1
  loadTeamList()
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  loadTeamList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadTeamList()
}

// 获取成员角色类型
const getMemberRoleType = (role) => {
  const types = {
    0: '', // 普通成员
    1: 'danger', // 队长
    2: 'warning' // 管理员
  }
  return types[role] || ''
}

// 获取成员角色文本
const getMemberRoleText = (role) => {
  const texts = {
    0: '普通成员',
    1: '队长',
    2: '管理员'
  }
  return texts[role] || '未知角色'
}

// 页面加载时获取队伍列表
onMounted(() => {
  loadTeamList()
})
</script>

<style scoped lang="scss">
.admin-teams {
  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .team-name {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .member-info {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .member-list {
    margin-top: 20px;
    
    .section-title {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 16px;
      padding-left: 8px;
      border-left: 4px solid var(--el-color-primary);
    }
  }
}
</style> 